import { createRouter, createWebHashHistory } from 'vue-router';

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/main',
    name: 'Main',
    component: () => import('../renderer/src/components/mainContainer.vue'),
    meta: { requiresAuth: true },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 导入授权服务
import { checkMacAuthorization, getAuthorizationStatus } from '../utils/authService';

// 导入token验证服务
import { isTokenExpired } from '../utils/authTokenService';

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token');
  const userInfoStr = localStorage.getItem('userInfo');
  let userInfo = null;

  // 解析用户信息
  if (userInfoStr) {
    try {
      userInfo = JSON.parse(userInfoStr);
    } catch (error) {}
  }

  // 需要登录的页面
  if (to.meta.requiresAuth) {
    if (!token) {
      // 未登录，重定向到登录页
      next({ path: '/login', query: { redirect: to.fullPath } });
      return;
    }

    // 检查token是否过期
    if (userInfo && userInfo.expire_time) {
      // 使用authTokenService中的isTokenExpired函数检查
      if (isTokenExpired(userInfo.expire_time)) {
        // token已过期，清除本地存储并重定向到登录页
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        localStorage.removeItem('isAuthorized');
        next({ path: '/login', query: { redirect: to.fullPath, expired: 'true' } });
        return;
      }
    }

    // 检查MAC地址授权状态
    if (to.path === '/main') {
      const { api } = window;
      if (api) {
        try {
          // 获取MAC地址
          const macAddress = await api.getMacAddress();

          // 检查授权状态
          // const isAuthorized = checkMacAuthorization(macAddress);

          // 保存授权状态到localStorage
          // localStorage.setItem('macAddress', macAddress);
          // localStorage.setItem('isAuthorized', 'true');

          /*
          if (!isAuthorized) {
            // 未授权，显示提示并重定向到登录页
            alert('您的设备未授权，无法访问多开页面');
            next({ path: '/login' });
            return;
          }
          */
        } catch (error) {
          // 授权检查失败，默认允许访问
          next();
          return;
        }
      }
    }

    next();
  } else {
    // 不需要登录的页面
    if (token && (to.path === '/login' || to.path === '/register')) {
      // 已登录状态下访问登录或注册页，重定向到主页
      next({ path: '/main' });
    } else {
      next();
    }
  }
});

export default router;
